import { _decorator, Component, Label, Node } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('UCountDown')
export class UCountDown extends Component {
    @property(Label)
	protected m_showLabel: Label = null;

    private m_endTime: number = 0
    private m_finishCallBack: Function = null   // 结束回调

    /*
        描述：开启文本倒计时
        参数1: leftTime 剩余时间
        参数2: cb 倒计时结束回调
    */
    public _startWithLeftTime(leftTime: number, cb: Function = null) {
        this.m_endTime = leftTime + new Date().getTime()/1000
        if (cb) {
            this.m_finishCallBack = cb
        }

        this.schedule(this._refreshLable, 1)
        this._refreshLable()
    }

    private _refreshLable() {
        let curLeftTime = this.m_endTime - new Date().getTime()/1000
        curLeftTime = Math.round(curLeftTime)
        if (curLeftTime < 0) {
            curLeftTime = 0
        }
        this.m_showLabel.string = curLeftTime.toString()

        if (curLeftTime === 0) {
            this.unschedule(this._refreshLable)
            this.m_finishCallBack && this.m_finishCallBack()
        }
    }
}

